<?php

namespace App\Http\Controllers\Members\Members;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Repositories\MembersRepository;
use Storage;
class IndexController extends Controller
{
  public function __construct()
	{
	 	$this->middleware('auth:members', ['except' => ['Check','Register','Exist']]);
	 
	}
	public function Refresh()
	{
		return $this->respondWithToken(auth('members')->refresh());
	}
	public function Check()
	{
		return response()->json(['code'=>0,'auth' => auth('members')->check()]);

	}
	/**
	 *  修改自己的密码
	 */
	public function ChangePassword(Request $request, MembersRepository $MembersRepository)
	{
		$user = auth('members')->user();
		$credentials = [
			'password' => trim($request->input('OLDPassword')),
			'accountname' => $user->AccountName
		];
 
		if ($token = auth('members')->attempt($credentials)) {

			$MembersRepository->update(['Password' => bcrypt(trim($request->input('Password')))], $user->ID);
			return response()->json([
				'code' => 0,
				'access_token' => $token,
				'token_type' => 'bearer',
				'expires_in' => auth('members')->factory()->getTTL() * 60,
				'result' => auth('members')->user(),
				'message' => '密码修改成功'
			]);

		}
		else {
			return response()->json(['code' => 1, 'message' => '旧密码错误']);
		}

	}
	public function Register(MembersRepository $MembersRepository, Request $request)
	{
		 
			$Users = [
			'ID' => $this->nextid(),
			'CreateTime' => time(),
			'Nickname' => trim($request->input('AccountName')),
			'AccountName' => trim($request->input('AccountName')),
			'Password' => bcrypt(trim($request->input('Password'))),
			'Avatar' => '',
			'Status'=>0,
		];

		if (!$MembersRepository->existsWhere(['AccountName' => $Users['AccountName']])) {
			if ($MembersRepository->create($Users)) {
				$credentials = [
					'accountname' => trim($request->input('AccountName')),
					'password' =>trim($request->input('Password')),
					'Status'=>0,
				];
				 if ($token = auth('members')->attempt($credentials)) {
            $userInfo =  auth('members')->user(); 
		        $userInfo->update([
		            'LoginTime' => time(), 'LastIp' => $_SERVER["REMOTE_ADDR"], 'LoginCount' => $userInfo->LoginCount + 1
		        ]);
		        
		        	return response()->json([
							'code' => 0,
							'access_token' => $token,
							'token_type' => 'bearer',
							'expires_in' => auth('members')->factory()->getTTL() * 60,
							'result' => $userInfo,
							'message'=>'注册成功！',
							]);
		       
        }else{
        	
        	  return response()->json(['code' => 0, 'message' => '注册成功！']);
        	}
			}
			else {
				return response()->json(['code' => 1, 'message' => '注册失败！']);
			}
		}
		else {
			return response()->json(['code' => 1, 'message' => '账号名已经被占用！']);
		}
	}
	public function Exist(MembersRepository $MembersRepository, Request $request)
	{
		$AccountName = trim($request->input('AccountName'));
		$ID = trim($request->input('ID'));
		if(empty($ID))
		{
			$ID='0';
		}
		return response()->json(['code' => 0, 'result' => $MembersRepository->existsWhere([['AccountName', '=', $AccountName], ['ID', '<>', $ID]])]);
	}
	/*
	 *  会员上传头像
	 */
	public function UploadFace(Request $request, MembersRepository $MembersRepository)
	{
		$user = auth('members')->user();
		if ($request->hasFile('file')) {

			$file = $request->file('file');
 
			$ext = $file->getClientOriginalExtension(); 
			$realPath = $file->getRealPath();  
			//$type = $file->getClientMimeType();  
 
			$filename = uniqid() . '.' . $ext;
			//Log::info($filename);
			if (in_array(strtolower($file->extension()), ['jpeg', 'jpg', 'gif', 'gpeg', 'png'])) {
				// 使用我们新建的uploads本地存储空间（目录）
				//这里的upload是配置文件的名称
				$bool = Storage::disk('oss')->put("/avatar/members/" . $filename, file_get_contents($realPath));
				//判断是否创建成功
				if (!$bool) {
					return response()->json(['code' => 1, 'message' => '头像上传失败']);
				}
				else {
					if (trim($user->Avatar) != '') {
						//删除旧的头像
						Storage::disk('oss')->delete("/avatar/members/" . $user->Avatar);
					}
					$MembersRepository->update(['Avatar' => $filename], $user->ID);
					return response()->json(['code' => 0, 'message' => '头像上传成功', 'result' => $filename]);
				}
			}
			else {
				return response()->json(['code' => 1, 'message' => '请选择图片文件']);
			}
		}

	}
	 
 
	 /**
	 * 会员修改资料
	 */
	public function SaveInfo(MembersRepository $MembersRepository, Request $request)
	{
	
		$requestData = [
			'Nickname' => trim($request->input('Nickname')),
			'Name' => trim($request->input('Name')),
			'Birthday' => $request->input('Birthday'),
			'Gender' => $request->input('Gender'),
			'Beginn'=> $request->input('Beginn'),
			'PlaceResidence' => trim($request->input('PlaceResidence')),
			'AreaID' => trim($request->input('AreaID')),
			'MobileTelephone' => trim($request->input('MobileTelephone')),
			'QQ' => trim($request->input('QQ')),
			'Wechat' => trim($request->input('Wechat')),
		  'Email' => trim($request->input('Email')),
		];
		$user = auth('members')->user();
		$ID = $user->ID;
		$MembersRepository->update($requestData, $ID);
		return response()->json(['code' => 0, 'message' => '完成资料设置']);

	}
		public function GetInfo(MembersRepository $MembersRepository, Request $request)
	{
	 
		$user = auth('members')->user();
    $user->Avatar=empty($user->Avatar)?'':$this->ToImageURL("/avatar/members/".$user->Avatar);
		return response()->json(['code' => 0, 'result' => $user]);

	}
	protected function respondWithToken($token)
	{
		return response()->json([
			'code' => 0,
			'access_token' => $token,
			'token_type' => 'bearer',
			'expires_in' => auth('members')->factory()->getTTL() * 60,
			'result' => auth('members')->user(),
		]);
	}
}
